package com.wdh.kjs.fragment;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.wdh.kjs.Adapter.IM_investrecord_Adapter;
import com.wdh.kjs.Adapter.IM_raisesuccess_Adapter;
import com.wdh.kjs.Adapter.IM_raising_Adapter;
import com.wdh.kjs.R;
import com.wdh.kjs.http.Httpurl;
import com.wdh.kjs.model.JsonModel_my;
import com.wdh.kjs.util.DateUtilChange;
import com.wdh.kjs.util.DateUtils;
import com.wdh.kjs.util.ToastUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by feifei on 2016/8/18.
 */
public class Fragement_InvestManage_Success  extends Fragment {

    private PullToRefreshListView listView;

    private IM_raisesuccess_Adapter IM_raise_three;

    private HashMap<String, String> maps = new HashMap<String, String>();

    public int QUERY_TYPE=0;
    private JsonModel_my jsonModel_my;
    private String partyId;
    private String time;
    public static int page ;
    public static int rows = 3;
    public static int totalrecords = 0;
    public static boolean mLoading = true;
    private List<HashMap<String, String>> datas;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_investmanage_my, container, false);
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("logininfo", Context.MODE_PRIVATE);
        partyId = sharedPreferences.getString("loginToken", "");
        initView(view);
        loadData();
//        Log.i("msg","111");
        return view;
    }
    private void initView(View view) {
//        scrollView=(ScrollView)view.findViewById(R.id.fragment_investmanage_scrollview);
//        scrollView.smoothScrollTo(0, 0);
        listView=(PullToRefreshListView)view.findViewById(R.id.fragment_investmanage_listview_MY);
    }
    private void loadData()
    {


                page = 1;
                RequestParams params_3 = new RequestParams();
                params_3.addBodyParameter("partyId", partyId);
                params_3.addBodyParameter("page", page + "");
                params_3.addBodyParameter("rows", rows + "");
                params_3.addBodyParameter("itemStatus", "9");

                HttpUtils http_3 = new HttpUtils();
                http_3.send(HttpRequest.HttpMethod.POST, Httpurl.URL_IM_RAISE, params_3, new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        Gson gson = new Gson();
                        jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                        totalrecords = jsonModel_my.getTotalrecords();
                        if (jsonModel_my.success) {

                            IM_raise_three = new IM_raisesuccess_Adapter(getContext(), initListViewData());
                            listView.setAdapter(IM_raise_three);
                            listView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
                            listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {

                                // 下拉Pulling Down
                                @Override
                                public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                                    // 下拉的时候数据重置
                                }

                                // 上拉Pulling Up
                                @Override
                                public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                                    // 上拉的时候添加选项

                                    String label = DateUtils.formatDateTime(getActivity().getApplicationContext(), System.currentTimeMillis(),
                                            DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);


                                    refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                                    new GetDataTask().execute();


                                }

                            });
                        }
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        ToastUtils.showShort(getActivity(), "网络异常！");
                    }
                });


    }
    private class GetDataTask extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (totalrecords > datas.size()) {

                page += 1;
                try {
                    getMoreList();

                } catch (Exception e) {
                    page -= 1;
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {

            if (mLoading == false)
                ToastUtils.showShort(getActivity(), "已无更多数据！");
            listView.onRefreshComplete();

            super.onPostExecute(aVoid);

        }
    }

    private void getMoreList() {
        RequestParams params_2 = new RequestParams();
        params_2.addBodyParameter("partyId", partyId);
        params_2.addBodyParameter("page", page+"");
        params_2.addBodyParameter("rows", rows+"");
        params_2.addBodyParameter("itemStatus", "9");



        HttpUtils http_2 = new HttpUtils();
        http_2.send(HttpRequest.HttpMethod.POST, Httpurl.URL_IM_RAISE, params_2, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                Gson gson = new Gson();
                jsonModel_my = gson.fromJson(responseInfo.result, JsonModel_my.class);
                totalrecords = jsonModel_my.getTotalrecords();
                if (jsonModel_my.success) {

                    for(int i=0;i<jsonModel_my.getInvestitems().size();i++){
                        Log.i("msg","raise-111");
//                    String time = DateUtilChange.timestamp2String(jsonModel_my.getInvestitems().get(i).getInterestStartDate(),DateUtilChange.DEFAULT_DAY_FORMAT);
                        int annualRate = new BigDecimal(jsonModel_my.getInvestitems().get(i).getGdAnnualizedBenefitRate().toString()).multiply(new BigDecimal(100 + "")).intValue();

                        HashMap<String, String> hashMap = new HashMap<>();
                        hashMap.put("name", jsonModel_my.getInvestitems().get(i).getItemName().toString());
                        hashMap.put("annualRate",annualRate+"%");
                        hashMap.put("projectTime", jsonModel_my.getInvestitems().get(i).getInterestDays()+"天");

                        if(jsonModel_my.getInvestitems().get(i).getGdBenefitMode()== 0){
                            hashMap.put("repayType", "到期一次性还本付息");
                        }else if(jsonModel_my.getInvestitems().get(i).getGdBenefitMode()== 1)
                        { hashMap.put("repayType", "按月付息到期还本"); };

                        hashMap.put("totalMoney", "￥"+new BigDecimal(jsonModel_my.getInvestitems().get(i).getRaiseMoney().toString()).setScale(2)+"元");
                        hashMap.put("state", "融资中");

                        hashMap.put("starttime", time);


                        datas.add(hashMap);
                    }
                    if (datas.size() == totalrecords)
                        mLoading = false;

                    IM_raise_three.notifyDataSetChanged();


                }
            }
            @Override
            public void onFailure(HttpException error, String msg) {
                ToastUtils.showShort(getActivity(), "网络异常！");
            }
        });
    }

    private List<HashMap<String, String>> initListViewData()
    {
        datas=new ArrayList<>();
        for(int i= 0;i<jsonModel_my.getInvestitems().size();i++){
                    if (jsonModel_my.getInvestitems().get(i).getInterestStartDate()!=-1){
                        time = DateUtilChange.timestamp2String(jsonModel_my.getInvestitems().get(i).getInterestStartDate(), DateUtilChange.DEFAULT_DAY_FORMAT);}
                    else {
                        time = "";
                    }
                    int annualRate = new BigDecimal(jsonModel_my.getInvestitems().get(i).getGdAnnualizedBenefitRate().toString()).multiply(new BigDecimal(100 + "")).intValue();

                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put("name", jsonModel_my.getInvestitems().get(i).getItemName().toString());
                    hashMap.put("annualRate", annualRate+"%");
                    hashMap.put("projectTime", jsonModel_my.getInvestitems().get(i).getInterestDays()+"天");

                    if(jsonModel_my.getInvestitems().get(i).getGdBenefitMode()== 0){
                        hashMap.put("repayType", "到期一次性还本付息");
                    }else if(jsonModel_my.getInvestitems().get(i).getGdBenefitMode()== 1)
                    { hashMap.put("repayType", "按月付息到期还本"); };

                    hashMap.put("totalMoney", "￥"+new BigDecimal(jsonModel_my.getInvestitems().get(i).getRaiseMoney().toString()).setScale(2)+"元");
                    hashMap.put("state", "募集成功结束");
                    hashMap.put("starttime", time);
                    datas.add(hashMap);
                }

        return datas;
    }

}
